<?php

namespace App\Admin\Actions\Post;

use App\Model\CoinLog;
use App\Model\Message;
use App\Model\User;
use App\Model\UserCoin;
use App\Model\UserProfile;
use App\Model\UserProfilePersonal;
use App\Model\Withdraw;
use Encore\Admin\Actions\BatchAction;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class UpdateWithdrawOk extends BatchAction
{
    public $name = "<a class='report-posts btn btn-sm btn-info'><i class='fa fa-info-circle'></i>云账号提现</a>";
    protected $selector = '.report-posts';

    public function handle(Collection $collection, Request $request)
    {
        $ids = $request->input('_key');

        $ids = is_array($ids) ? $ids :  explode(',', $ids);

        if(count($ids)<=0){
            return $this->response()->error('请选择要操作的ID')->refresh();
        }
        if(count($ids)>20){
            return $this->response()->error('一次最多只能选择20个哦！')->refresh();
        }


        $ret = ['ret' => 0, 'message' => '操作成功！'];
        $uidscount = 0;
        $uids = [];
        $logId = [];
        foreach ($ids as $key => $val){
            $id = $val;
            DB::beginTransaction();
            try {
                $record = Withdraw::find($id);
                //记录不存在
                if (!$record) {
                    DB::commit();
                    continue;
                }

                //状态不等于审核状态不给与操作
                if ($record->status != Withdraw::STATUS_ING) {
                    $uidscount = $uidscount+1;
                    $logId[] = $id;
                    DB::commit();
                    continue;
                }
                //判断用户状态
                $userInfo = User::find($record->user_id);
                if(empty($userInfo) || $userInfo->status != 0){
                    $uidscount = $uidscount+1;
                    $logId[] = $id;
                    DB::commit();
                    continue;
                }

                $payWay = request('extra','yzh');
                $withdrawWay = '';
                switch ($payWay) {
                    case 'yzh':
                        $ret = Withdraw::doYzhOrder($record->toArray());
                        $withdrawWay = isset($ret['bind_type']) && $ret['bind_type'] == UserProfilePersonal::BIND_TYPE_ALI ? '支付宝' : '银行卡';
                        Log::info(__CLASS__ . "WithdrawId:{$id}==Payway:{$payWay}==UserId:{$record->user_id}==" . json_encode($ret));
                        break;
                    case 'wechat':
                    case 'alipay':
                        Log::info(__CLASS__ . "WithdrawId:{$id}==Payway:{$payWay}==UserId:{$record->user_id}");
                        break;
                    //杉德
                    case 'sand':
                        $withdrawWay = '银行卡';
                        $ret = Withdraw::doSandOrder($record->toArray());
                        Log::info(__CLASS__ . "WithdrawId:{$id}==Payway:{$payWay}==UserId:{$record->user_id}==" . json_encode($ret));
                        break;
                    case 'mst_alipay':
                    case 'mst_alipay_bank':
                        $withdrawWay = ($payWay == "mst_alipay") ? "支付宝" : '银行卡';
                        $ret = Withdraw::doMstOrder($record->toArray(), $payWay);
                        Log::info(__CLASS__ . "WithdrawId:{$id}==Payway:{$payWay}==UserId:{$record->user_id}==" . json_encode($ret));
                        break;
                }
                //提现审核已经通过
                if ($ret['ret'] == 0) {
                    $time = date('Y年m月d日', strtotime((string)$record->created_at));
                    $pushMsg = "你于{$time}申请的提现已通过审核，请注意查收你的{$withdrawWay}账号！";
                    Message::pushSystem($record->user_id, $pushMsg, '提现通知');
                    Withdraw::where('id', $id)->limit(1)->update([
                        'status' => Withdraw::STATUS_OK,
                        'withdraw_way' => $payWay
                    ]);

                }
                DB::commit();
            } catch (Exception $e) {
                DB::rollBack();
                Log::info(__CLASS__ . "==WithdrawId:{$id}==Exception:" . $e->getMessage());
            }
        }
        $count = count($ids);
        $success = (int)$count-$uidscount;
        if($uidscount>0){
            $logIdStr = implode(',',$logId);
            $successStr = '成功条数:（'.$success.'条） 失败条数：（'.$uidscount.'条） 失败的记录ID：'.$logIdStr;
            return $this->response()->success($successStr)->refresh();
        }

        return $this->response()->success('修改成功')->refresh();
    }

    public function dialog($ids = '')
    {
        $this->confirm('确认执行该操作么？');
    }

    public function html()
    {
        return "<a class='report-posts btn btn-sm btn-info'><i class='fa fa-info-circle'></i>允许提现</a>";
    }
}
